<template>
  <div class="schema-manager">
    <el-row :gutter="20">
      <!-- 左侧：表列表 -->
      <el-col :span="8">
        <el-card class="table-list-card">
          <template #header>
            <div class="card-header">
              <span>数据表</span>
              <div class="header-actions">
                <el-select v-model="selectedCase" value-key="id" placeholder="选择案件同步" size="small" style="width: 140px" clearable @change="syncCaseTables">
                  <el-option v-for="c in cases" :key="c.id" :label="c.case_name" :value="c" />
                </el-select>
                <el-button type="primary" link size="small" @click="syncTables" :loading="syncing">
                  <el-icon><Refresh /></el-icon>
                </el-button>
                <el-button type="primary" size="small" @click="openCreateDialog">
                  <el-icon><Plus /></el-icon> 新建
                </el-button>
              </div>
            </div>
          </template>
          
          <div v-loading="loading" class="table-list">
            <div 
              v-for="table in schemas" 
              :key="table.name" 
              class="table-item"
              :class="{ active: selectedTable?.name === table.name }"
              @click="selectTable(table)"
            >
              <div class="table-info">
                <el-icon v-if="table.is_system" class="system-icon"><Lock /></el-icon>
                <el-icon v-else class="user-icon"><Document /></el-icon>
                <div class="table-details">
                  <span class="table-name">{{ table.display_name }}</span>
                  <span class="table-code">{{ table.name }}</span>
                </div>
              </div>
              <div class="table-actions">
                <el-tag v-if="table.db_type === 'case'" size="small" type="warning">案件</el-tag>
                <el-tag v-else-if="table.is_system" size="small" type="info">系统</el-tag>
                <el-button 
                  v-if="isDev" 
                  link 
                  type="danger" 
                  size="small" 
                  @click.stop="deleteTable(table)"
                >
                  删除
                </el-button>
              </div>
            </div>
            
            <el-empty v-if="schemas.length === 0" description="暂无数据表" />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：字段详情 -->
      <el-col :span="16">
        <el-card v-if="selectedTable" class="field-detail-card">
          <template #header>
            <div class="card-header">
              <div class="table-title">
                <span class="title">{{ selectedTable.display_name }}</span>
                <el-button link type="primary" @click="openEditTableDialog" style="margin-left: 8px">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <code class="code">{{ selectedTable.name }}</code>
              </div>
              <el-button 
                v-if="!selectedTable.is_system || isDev" 
                type="primary" 
                size="small" 
                @click="openAddFieldDialog"
              >
                <el-icon><Plus /></el-icon> 添加字段
              </el-button>
            </div>
          </template>

          <div class="table-meta">
            <div class="meta-item">
              <span class="meta-label">描述:</span>
              <span class="meta-value">{{ selectedTable.description || '无' }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">字段数:</span>
              <span class="meta-value">{{ selectedTable.fields?.length || 0 }}</span>
            </div>
          </div>

          <el-divider content-position="left">字段列表</el-divider>

          <el-table :data="selectedTable.fields" style="width: 100%; flex: 1" height="100%">
            <el-table-column prop="name" label="字段名" width="180">
              <template #default="{ row }">
                <code>{{ row.name }}</code>
              </template>
            </el-table-column>
            <el-table-column prop="displayName" label="显示名" width="150" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag size="small">{{ fieldTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="属性" width="120">
              <template #default="{ row }">
                <el-tag v-if="row.required" size="small" type="warning">必填</el-tag>
                <el-tag v-if="row.primaryKey" size="small" type="danger">主键</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="!selectedTable.is_system || isDev">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="openEditFieldDialog(row)">编辑</el-button>
                <el-button link type="danger" size="small" @click="removeField(row.name)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        
        <el-empty v-else description="请从左侧选择一个表" />
      </el-col>
    </el-row>

    <!-- 新建表对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建数据表" width="500px">
      <el-form :model="newTableForm" label-width="100px" ref="createFormRef" :rules="createRules">
        <el-form-item label="表名" prop="name">
          <el-input v-model="newTableForm.name" placeholder="如: logistics_data" />
          <div class="form-tip">只能包含小写字母、数字和下划线</div>
        </el-form-item>
        <el-form-item label="显示名" prop="display_name">
          <el-input v-model="newTableForm.display_name" placeholder="如: 物流数据" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newTableForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createTable" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加字段对话框 -->
    <el-dialog v-model="showAddFieldDialog" title="添加字段" width="400px">
      <el-form :model="newFieldForm" label-width="80px" ref="fieldFormRef" :rules="fieldRules">
        <el-form-item label="字段名" prop="name">
          <el-input v-model="newFieldForm.name" placeholder="如: amount" />
        </el-form-item>
        <el-form-item label="显示名" prop="displayName">
          <el-input v-model="newFieldForm.displayName" placeholder="如: 金额" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="newFieldForm.type" style="width: 100%">
            <el-option label="文本" value="string" />
            <el-option label="整数" value="integer" />
            <el-option label="浮点数" value="float" />
            <el-option label="日期时间" value="datetime" />
            <el-option label="布尔" value="boolean" />
          </el-select>
        </el-form-item>
        <el-form-item label="必填">
          <el-switch v-model="newFieldForm.required" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddFieldDialog = false">取消</el-button>
        <el-button type="primary" @click="addField" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑字段对话框 -->
    <el-dialog v-model="showEditFieldDialog" title="编辑字段" width="400px">
      <el-form :model="editFieldForm" label-width="80px" ref="editFieldFormRef" :rules="fieldRules">
        <el-form-item label="字段名">
          <el-input v-model="editFieldForm.name" disabled />
        </el-form-item>
        <el-form-item label="显示名" prop="displayName">
          <el-input v-model="editFieldForm.displayName" placeholder="如: 金额" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="editFieldForm.type" style="width: 100%">
            <el-option label="文本" value="string" />
            <el-option label="整数" value="integer" />
            <el-option label="浮点数" value="float" />
            <el-option label="日期时间" value="datetime" />
            <el-option label="布尔" value="boolean" />
          </el-select>
        </el-form-item>
        <el-form-item label="属性">
          <el-checkbox v-model="editFieldForm.required">必填</el-checkbox>
          <el-checkbox v-model="editFieldForm.primaryKey">主键</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditFieldDialog = false">取消</el-button>
        <el-button type="primary" @click="updateField" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑表信息对话框 -->
    <el-dialog v-model="showEditTableDialog" title="编辑表信息" width="500px">
      <el-form :model="editTableForm" label-width="100px" ref="editTableFormRef" :rules="createRules">
        <el-form-item label="表名">
          <el-input v-model="editTableForm.name" disabled />
        </el-form-item>
        <el-form-item label="显示名" prop="display_name">
          <el-input v-model="editTableForm.display_name" placeholder="如: 物流数据" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editTableForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditTableDialog = false">取消</el-button>
        <el-button type="primary" @click="updateTable" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import { Plus, Refresh, Lock, Document, Edit } from '@element-plus/icons-vue';

const schemas = ref([]);
const cases = ref([]);
const selectedCase = ref(null);
const selectedTable = ref(null);
const loading = ref(false);
const syncing = ref(false);
const submitting = ref(false);

const isDev = import.meta.env.DEV;

const showCreateDialog = ref(false);
const showAddFieldDialog = ref(false);
const showEditFieldDialog = ref(false);
const showEditTableDialog = ref(false);

const createFormRef = ref(null);
const fieldFormRef = ref(null);
const editFieldFormRef = ref(null);
const editTableFormRef = ref(null);

const newTableForm = reactive({
  name: '',
  display_name: '',
  description: ''
});

const newFieldForm = reactive({
  name: '',
  displayName: '',
  type: 'string',
  required: false,
  primaryKey: false
});

const editFieldForm = reactive({
  name: '',
  displayName: '',
  type: 'string',
  required: false,
  primaryKey: false
});

const editTableForm = reactive({
  name: '',
  display_name: '',
  description: ''
});

const createRules = {
  name: [
    { required: true, message: '请输入表名', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '格式不正确', trigger: 'blur' }
  ],
  display_name: [
    { required: true, message: '请输入显示名', trigger: 'blur' }
  ]
};

const fieldRules = {
  name: [
    { required: true, message: '请输入字段名', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '格式不正确', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入显示名', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ]
};

const fieldTypeLabels = {
  string: '文本',
  integer: '整数',
  float: '浮点',
  datetime: '日期',
  boolean: '布尔',
  json: 'JSON'
};

const fieldTypeLabel = (type) => fieldTypeLabels[type] || type;

onMounted(() => {
  fetchSchemas();
  fetchCases();
});

async function fetchCases() {
  try {
    cases.value = await window.electronAPI.case.getAll();
  } catch (error) {
    console.error('获取案件列表失败:', error);
  }
}

async function fetchSchemas() {
  loading.value = true;
  try {
    schemas.value = await window.electronAPI.schema.getAll();
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message);
  } finally {
    loading.value = false;
  }
}

async function syncTables() {
  syncing.value = true;
  try {
    // Sync main tables
    await window.electronAPI.schema.sync();
    
    // Sync case tables if a case is selected
    if (selectedCase.value) {
      await window.electronAPI.schema.syncCase(
        selectedCase.value.id,
        selectedCase.value.db_path
      );
    }
    
    await fetchSchemas();
    ElMessage.success('同步完成');
  } catch (error) {
    ElMessage.error('同步失败: ' + error.message);
  } finally {
    syncing.value = false;
  }
}

async function syncCaseTables() {
  if (!selectedCase.value) return;
  
  syncing.value = true;
  try {
    const result = await window.electronAPI.schema.syncCase(
      selectedCase.value.id,
      selectedCase.value.db_path
    );
    await fetchSchemas();
    ElMessage.success(`已同步案件表: ${result.tables?.join(', ') || '无新表'}`);
  } catch (error) {
    ElMessage.error('同步案件表失败: ' + error.message);
  } finally {
    syncing.value = false;
  }
}

function selectTable(table) {
  selectedTable.value = table;
}

function openCreateDialog() {
  newTableForm.name = '';
  newTableForm.display_name = '';
  newTableForm.description = '';
  showCreateDialog.value = true;
}

async function createTable() {
  if (!createFormRef.value) return;
  
  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        await window.electronAPI.schema.create({
          name: newTableForm.name,
          display_name: newTableForm.display_name,
          description: newTableForm.description,
          fields: []
        });
        ElMessage.success('创建成功');
        showCreateDialog.value = false;
        await fetchSchemas();
      } catch (error) {
        ElMessage.error('创建失败: ' + error.message);
      } finally {
        submitting.value = false;
      }
    }
  });
}

function openAddFieldDialog() {
  newFieldForm.name = '';
  newFieldForm.displayName = '';
  newFieldForm.type = 'string';
  newFieldForm.required = false;
  showAddFieldDialog.value = true;
}

async function addField() {
  if (!fieldFormRef.value || !selectedTable.value) return;
  
  await fieldFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        await window.electronAPI.schema.update(selectedTable.value.name, {
          addFields: [{
            name: newFieldForm.name,
            displayName: newFieldForm.displayName,
            type: newFieldForm.type,
            required: newFieldForm.required,
            primaryKey: newFieldForm.primaryKey
          }]
        });
        ElMessage.success('字段添加成功');
        showAddFieldDialog.value = false;
        
        // Refresh
        await fetchSchemas();
        selectedTable.value = schemas.value.find(s => s.name === selectedTable.value.name);
      } catch (error) {
        ElMessage.error('添加失败: ' + error.message);
      } finally {
        submitting.value = false;
      }
    }
  });
}

function openEditFieldDialog(field) {
  editFieldForm.name = field.name;
  editFieldForm.displayName = field.displayName || field.name;
  editFieldForm.type = field.type;
  editFieldForm.required = field.required;
  editFieldForm.primaryKey = field.primaryKey;
  showEditFieldDialog.value = true;
}

async function updateField() {
  if (!editFieldFormRef.value) return;
  
  await editFieldFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        await window.electronAPI.schema.update(selectedTable.value.name, {
          modifyFields: [{
            name: editFieldForm.name,
            displayName: editFieldForm.displayName,
            type: editFieldForm.type,
            required: editFieldForm.required,
            primaryKey: editFieldForm.primaryKey
          }]
        });
        ElMessage.success('字段更新成功');
        showEditFieldDialog.value = false;
        await fetchSchemas();
        // 重新选中当前表以更新字段列表
        const updatedTable = schemas.value.find(t => t.name === selectedTable.value.name);
        if (updatedTable) selectedTable.value = updatedTable;
      } catch (error) {
        ElMessage.error('更新失败: ' + error.message);
      } finally {
        submitting.value = false;
      }
    }
  });
}

function openEditTableDialog() {
  if (!selectedTable.value) return;
  editTableForm.name = selectedTable.value.name;
  editTableForm.display_name = selectedTable.value.display_name;
  editTableForm.description = selectedTable.value.description;
  showEditTableDialog.value = true;
}

async function updateTable() {
  if (!editTableFormRef.value) return;
  
  await editTableFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        await window.electronAPI.schema.update(selectedTable.value.name, {
          display_name: editTableForm.display_name,
          description: editTableForm.description
        });
        ElMessage.success('表信息更新成功');
        showEditTableDialog.value = false;
        
        await fetchSchemas();
        // 重新选中
        const updated = schemas.value.find(s => s.name === selectedTable.value.name);
        if (updated) selectedTable.value = updated;
      } catch (error) {
        ElMessage.error('更新失败: ' + error.message);
      } finally {
        submitting.value = false;
      }
    }
  });
}

async function removeField(fieldName) {
  if (!selectedTable.value) return;
  
  try {
    await ElMessageBox.confirm(`确定要移除字段 "${fieldName}" 吗？`, '确认', {
      type: 'warning'
    });
    
    await window.electronAPI.schema.update(selectedTable.value.name, {
      removeFields: [fieldName]
    });
    ElMessage.success('字段已移除');
    
    await fetchSchemas();
    selectedTable.value = schemas.value.find(s => s.name === selectedTable.value.name);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败: ' + error.message);
    }
  }
}

// 核心系统表，不允许物理删除
const PROTECTED_TABLES = ['cases', 'global_configs', 'analyzer_profiles', 'ai_prompt_templates', 'sys_schemas'];

async function deleteTable(table) {
  // 提取真实表名（case_ 前缀的表需要去掉前缀）
  const realTableName = table.name.startsWith('case_') ? table.name.slice(5) : table.name;
  const isProtected = PROTECTED_TABLES.includes(realTableName);
  
  if (isProtected) {
    // 核心系统表只能删除元数据
    try {
      await ElMessageBox.confirm(
        `"${table.display_name}" 是核心系统表，只能删除元数据，物理表不会被删除。`,
        '确认删除',
        { type: 'warning'
      });
      await window.electronAPI.schema.delete(table.name, false);
      ElMessage.success('元数据已删除');
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败: ' + error.message);
      }
      return;
    }
  } else {
    // 非核心表可以选择物理删除
    try {
      await ElMessageBox.confirm(
        `确定要删除表 "${table.display_name}" (${table.name}) 吗？`,
        '确认删除',
        {
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonText: '物理删除（含数据）',
          cancelButtonText: '仅删除元数据',
          showClose: true
        }
      );
      
      await window.electronAPI.schema.delete(table.name, true);
      ElMessage.success('表已物理删除');
    } catch (error) {
      if (error === 'cancel') {
        try {
          await window.electronAPI.schema.delete(table.name, false);
          ElMessage.success('元数据已删除');
        } catch (err) {
          ElMessage.error('删除失败: ' + err.message);
          return;
        }
      } else if (error !== 'close') {
        ElMessage.error('删除失败: ' + error.message);
        return;
      } else {
        return;
      }
    }
  }
  
  if (selectedTable.value?.name === table.name) {
    selectedTable.value = null;
  }
  await fetchSchemas();
}
</script>

<style scoped>
.schema-manager {
  padding: 20px;
}

.table-list-card, .field-detail-card {
  height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
}

.field-detail-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.table-list {
  overflow-y: auto;
  flex: 1;
  max-height: calc(100vh - 280px);
}

.table-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: background-color 0.2s;
}

.table-item:hover {
  background-color: #f5f7fa;
}

.table-item.active {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.system-icon {
  color: #909399;
}

.user-icon {
  color: #409eff;
}

.table-details {
  display: flex;
  flex-direction: column;
}

.table-name {
  font-weight: 500;
}

.table-code {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
}

.table-title {
  display: flex;
  align-items: baseline;
  gap: 10px;
}

.table-title .title {
  font-size: 16px;
  font-weight: 600;
}

.table-title .code {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
}

.table-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.meta-item {
  display: flex;
  gap: 5px;
}

.meta-label {
  color: #909399;
}

.meta-value {
  color: #303133;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
